def validate_itunes_library_file(file):
	#this is a hack but will do for now
	if not file:
		return False
	return file.name == "iTunes Music Library.xml"
	
from models import Track
import plistlib
from django.utils.encoding import smart_str, smart_unicode

def storeTracksFromFile(file, user):
	filedata = ""
	for chunk in file.chunks():
		filedata += chunk

	plist = plistlib.readPlistFromString(filedata)
	for track in plist['Tracks'].values():
		title = ""
		if 'Name' in track:
			title = smart_str(track['Name'])

		artist = ""
		if 'Artist' in track:
			artist = smart_str(track['Artist'])

		playcount = 0
		if 'Play Count' in track:
			playcount = track['Play Count']

		thistrack = Track(title = title, artist = artist, play_count=playcount, date_added = track['Date Added'], user = user)
		thistrack.save()
			
from django.core.files.uploadhandler import FileUploadHandler
from django.core.cache import cache

class UploadProgressCachedHandler(FileUploadHandler):
    """
    Tracks progress for file uploads.
    The http post request must contain a header or query parameter, 'X-Progress-ID'
    which should contain a unique string to identify the upload to be tracked.
    """

    def __init__(self, request=None):
        super(UploadProgressCachedHandler, self).__init__(request)
        self.progress_id = None
        self.cache_key = None

    def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None):
		self.content_length = content_length
		if 'X-Progress-ID' in self.request.GET :
			self.progress_id = self.request.GET['X-Progress-ID']
		elif 'X-Progress-ID' in self.request.META:
			self.progress_id = self.request.META['X-Progress-ID']
		
		if self.progress_id:
			           
			self.cache_key = self.progress_id
	  		cache.set(self.cache_key, {'length': self.content_length,'uploaded' : 0})
			


    def new_file(self, field_name, file_name, content_type, content_length, charset=None):
        pass

    def receive_data_chunk(self, raw_data, start):
        if self.cache_key:
            data = cache.get(self.cache_key)
            if data:
		data['uploaded'] += self.chunk_size
            	cache.set(self.cache_key, data)
        return raw_data

    def file_complete(self, file_size):
        pass

    def upload_complete(self):
		pass
     #   if self.cache_key:
      #      cache.delete(self.cache_key)

from threading import Thread

class TracksFromFile(Thread):
	def __init__ (self, file, key):
		Thread.__init__(self)
		self.file = file
		self.key = key
	def run(self):
		cache.set(self.key, 'crunching')
		storeTracksFromFile(self.file, self.key)
		cache.delete(self.key)
			
